package com.ahpu.jym.messagealert;

import com.ahpu.jym.messagealert.tools.OptionsData;
import com.ahpu.jym.messagealert.ui.MessageAlertDailog;

import net.rim.blackberry.api.mail.Address;
import net.rim.blackberry.api.mail.BodyPart;
import net.rim.blackberry.api.mail.BodyPart.ContentType;
import net.rim.blackberry.api.mail.Folder;
import net.rim.blackberry.api.mail.Message;
import net.rim.blackberry.api.mail.MessagingException;
import net.rim.blackberry.api.mail.MimeBodyPart;
import net.rim.blackberry.api.mail.Multipart;
import net.rim.blackberry.api.mail.ServiceConfiguration;
import net.rim.blackberry.api.mail.Session;
import net.rim.blackberry.api.mail.Store;
import net.rim.blackberry.api.mail.TextBodyPart;
import net.rim.blackberry.api.mail.Transport;
import net.rim.blackberry.api.mail.event.FolderEvent;
import net.rim.blackberry.api.mail.event.FolderListener;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Backlight;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.Dialog;

public class MailListening implements FolderListener {

	/**文本消息 **/
	String _plainTextMessage = "";
	/**html 消息 **/
	String _htmlMessage = "";

	// public static String test = "";
	// public static final long RTSID_MY_APP = 0x4a7ff5e6940749b1L;


	public MailListening() {

	}

	/**
	 * 
	 *<h4>Title: WaitforConfig</h4>
	 *<p>Description: 邮件的配置</p>
	 */
	public void WaitforConfig() {
		//读取ServiceBook
		ServiceBook sb = ServiceBook.getSB();
		sb = ServiceBook.getSB();
		ServiceRecord[] srs = sb.getRecords();

		for (int cnt = srs.length - 1; cnt >= 0; --cnt) {

			if (srs[cnt].getCid().equals("CMIME")) {
				ServiceConfiguration sc = new ServiceConfiguration(srs[cnt]);
				Store store = Session.getInstance(sc).getStore();
				// store.addFolderListener(this);
				Folder[] folders = store.list();
				for (int foldercnt = folders.length - 1; foldercnt >= 0; --foldercnt) {
					Folder f = folders[foldercnt];
					recurse(f);
				}
			}
		}
	}

	/*
	 * 消息添加
	 * @see net.rim.blackberry.api.mail.event.FolderListener#messagesAdded(net.rim.blackberry.api.mail.event.FolderEvent)
	 */
	public void messagesAdded(FolderEvent e) {
		// TODO Auto-generated method stub
		// if (e.getMessage().isInbound()) {
		try {
			Message msg = e.getMessage(); // Retrieve the first message
			final Address from = msg.getFrom();

			final String subject = msg.getSubject();
			Object o = msg.getContent();
			// Verify that the message is not multipart
			// if (o instanceof String) {
			findEmailBody(o);
			// final String body = (String) o;

			// if (OptionsData.load().getMailstatus() == 0) {
			if (OptionsData.load().getMailstatus() == 0) {

				Application.getApplication().invokeLater(new Runnable() {

					public void run() {
						synchronized (Application.getEventLock()) {
							UiEngine ui = Ui.getUiEngine();

							ui.pushGlobalScreen(new MessageAlertDailog(true,
									from, _plainTextMessage + "\n"
											+ _htmlMessage, subject), 10,
									UiApplication.GLOBAL_QUEUE);
							if ((Display.getProperties() & Display.DISPLAY_PROPERTY_REQUIRES_BACKLIGHT) != 0
									&& OptionsData.load().getBacklight() == 0) {
								Backlight.enable(true, 30);
							}
						}
					}
				});
			}
			// }
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			errorAlert(e1.getMessage());
		}

		// }
	}

	public void messagesRemoved(FolderEvent e) {

	}

	/**
	 * 
	 *<h4>Title: readEmailBody</h4>
	 *<p>Description: 读取消息</p>
	 * @param mbp MimeBodyPart 消息体
	 */
	private void readEmailBody(MimeBodyPart mbp) {
		// Extract the content of the message.
		Object obj = mbp.getContent();
		String mimeType = mbp.getContentType();
		String body = null;
		if (obj instanceof String) {
			body = (String) body;
		} else if (obj instanceof byte[]) {
			body = new String((byte[]) obj);
		}
		if (mimeType.indexOf(ContentType.TYPE_TEXT_PLAIN_STRING) != -1) {
			_plainTextMessage = body;
			// Determine if all of the text body part is present.
			if (mbp.hasMore() && !mbp.moreRequestSent()) {
				try {
					Transport.more((BodyPart) mbp, true);
				} catch (Exception ex) {
					errorAlert("Exception: " + ex.getMessage());
				}
			}
		} else if (mimeType.indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) {
			_htmlMessage = body;
			// Determine if all of the HTML body part is present.
			if (mbp.hasMore() && !mbp.moreRequestSent()) {
				try {
					Transport.more((BodyPart) mbp, true);
				} catch (Exception ex) {
					errorAlert("Exception: " + ex.getMessage());
				}
			}
		}
	}

	/**
	 * 
	 *<h4>Title: findEmailBody</h4>
	 *<p>Description: 通过消息体来读消息</p>
	 * @param obj
	 */
	private void findEmailBody(Object obj) {
		// Reset the attachment flags.
		// boolean _hasSupportedAttachment = false;
		// boolean _hasUnsupportedAttachment = false;
		if (obj instanceof Multipart) {
			//多媒体文件
			Multipart mp = (Multipart) obj;
			for (int count = 0; count < mp.getCount(); ++count) {
				findEmailBody(mp.getBodyPart(count));
			}
		} else if (obj instanceof TextBodyPart) {
			//文本文件
			TextBodyPart tbp = (TextBodyPart) obj;
			readEmailBody(tbp);
		} else if (obj instanceof MimeBodyPart) {
			//MIME
			MimeBodyPart mbp = (MimeBodyPart) obj;
			if (mbp.getContentType().indexOf(ContentType.TYPE_TEXT_HTML_STRING) != -1) {
				readEmailBody(mbp);
			} else if (mbp.getContentType().equals(
					ContentType.TYPE_MULTIPART_MIXED_STRING)
					|| mbp.getContentType().equals(
							ContentType.TYPE_MULTIPART_ALTERNATIVE_STRING)) {
				// The message has attachments or we are at the top level of the
				// message.
				// Extract all of the parts within the MimeBodyPart message.
				findEmailBody(mbp.getContent());
				// } else if (obj instanceof SupportedAttachmentPart) {
				// _hasSupportedAttachment = true;
				// } else if (obj instanceof UnsupportedAttachmentPart) {
				// _hasUnsupportedAttachment = true;
			}
		}
	}

	/**
	 * 
	 *<h4>Title: readEmailBody</h4>
	 *<p>Description: 读取消息体  文本消息</p>
	 * @param tbp 文本消息
	 */
	private void readEmailBody(TextBodyPart tbp) {
		_plainTextMessage = (String) tbp.getContent();
		if (tbp.hasMore() && !tbp.moreRequestSent()) {
			try {
				Transport.more((BodyPart) tbp, true);
			} catch (Exception ex) {
				errorAlert("Exception: " + ex.getMessage());
			}
		}
	}

	/**
	 * 
	 *<h4>Title: recurse</h4>
	 *<p>Description: 文件夹的递归查找</p>
	 * @param f 文件夹
	 */
	public void recurse(Folder f) {
		if (f.getType() == Folder.INBOX) {
			f.addFolderListener(this);
		}
		Folder[] farray = f.list();
		for (int fcnt = farray.length - 1; fcnt >= 0; --fcnt) {
			recurse(farray[fcnt]);
		}
	}

	/**
	 * 
	 *<h4>Title: errorAlert</h4>
	 *<p>Description: 错误消息</p>
	 * @param msg 消息
	 */
	private void errorAlert(String msg) {
		synchronized (Application.getEventLock()) {
			UiEngine ui = Ui.getUiEngine();
			Screen screen = new Dialog(Dialog.D_OK, msg, Dialog.OK,
					Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
					Manager.VERTICAL_SCROLL);
			ui.pushGlobalScreen(screen, 10, UiEngine.GLOBAL_QUEUE);
		}
	}

}
